
package com.scalar.chiptrack.operations.process.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.process.ProcessStep;
import com.scalar.chiptrack.operations.process.Upload;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.process.dao.MarkAndPackDAO;
import com.scalar.chiptrack.operations.process.dao.ProcessTrackDAO;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.VendorLocationDAO;
import com.scalar.chiptrack.operations.process.forms.MarkAndPackForm;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.User;

public class MarkAndPackAction extends ChipTrackAction {
    
    private static final String STEP_TYPE = "Mark & Pack";
    
    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) 
                                  throws Exception {
        
        String action = request.getParameter("action");
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute (SessionKeys.USER_KEY);
		if (user == null)
		{
			return (mapping.findForward ("login"));
		}
        HashMap errors = new HashMap();

        if ((action != null) && (action.equalsIgnoreCase("save"))) 
        {
            MarkAndPackForm mpForm = (MarkAndPackForm) form;
            
            DBTransaction dbTransaction = null;
            boolean success = false;
            
            int processStepId = -1;
			processStepId = mpForm.getProcessStepId();
            
			//added by ravikanth on 18 Aug 2003 to check for duplicate part numbers in Product Map Table
			String[] partNumbers = new String[mpForm.getDupProductName().length+1];
			partNumbers[0] = mpForm.getProductName();
			for(int i=0; i < mpForm.getDupProductName().length ; i++)
			{
				partNumbers[i+1] = mpForm.getDupProductName()[i];
			}
			// added by ravikanth on 16 Sep 2003 
			// check for duplicates in Product_Map_Table
			String dupNames = ProductDao.checkDupInProductMapTable(partNumbers,processStepId,STEP_TYPE);
			if( dupNames.length() > 0 )
			{
				 ArrayList vendorLocations = null;
				 errors.put ("Part Numbers Already exists ", dupNames );
                 // changed by hareesh on 27th Septemeber 2003
                 // -- START --
                 vendorLocations = getAllVendorLocations( request );
                 if(vendorLocations == null) {
				    if(processStepId!=-1)
				    {
					    vendorLocations = VendorDAO.getMarkAndPackLocations (processStepId);
				    }
				    else
				    {
					    vendorLocations = VendorDAO.getMarkAndPackLocations ();
				    }
                 }
                 // -- END --
				 request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
				 request.setAttribute( "classStoreForm" , mpForm );
				 request.setAttribute( "vendorLocations" , vendorLocations );
				 return ( mapping.findForward("failure") );
			}
			// upto here
            try 
            {
                // start transaction 
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();
				
				ArrayList locations = getVendorLocations(request);
				
				if(processStepId==-1)
				{
                    // added by hareesh on 8th September 2003
                    // -- START --
                    // Step 0
                    // to check name "part number" whether it exists already for another product or not.
                     boolean result = false;
                     if ( ( mpForm.getProductName() !=null ) && ( mpForm.getOldProductName() !=null ) ) 
                     {
	                     if( ! mpForm.getOldProductName().trim().equals( mpForm.getProductName().trim() ) )
                         {
    	                     result = ProcessTrackDAO.checkPartNumberExistsInTestBinAndFGBraodAndKit ( mpForm.getProductName().trim());
                         }
                     }
                     if (result == true )
                     {
                         errors.put( "Duplicate Part Number","Another Product has already present with this Part Number : "+ mpForm.getProductName().trim());
                     }
                     if ((errors != null) && (errors.isEmpty() == false)) 
                     {
                        request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
                     }
                     else 
                     {
                    		// -- END --
                            // Step 1
                            // insert a record into Process_Step table and get the process step id
                            processStepId = ProcessStep.getProcessStepID (dbTransaction, STEP_TYPE, STEP_TYPE, mpForm.getComments());
                            //System.out.println ("process StepId = " + processStepId);

                            // Step 2
                            // Upload procedure document
                            int procedureDocId = Upload.getProcedureDocID (dbTransaction,
                                                                              STEP_TYPE, // Mark & Pack
                                                                              mpForm.getProcedureDocNumber(),
                                                                              mpForm.getProcedureDocFile());

                            // Step 3
                            // Upload marking diagram file
                            int markingDiagramId = Upload.getMarkingDiagramDocID (dbTransaction,
                                                                                     STEP_TYPE, // Mark & Pack
                                                                                     mpForm.getMarkingDiagramNumber(),
                                                                                     mpForm.getMarkingDiagramFile());

                            // STEP 4
                            // insert new row in Mark_Pack Table
                            MarkAndPackDAO.storeMarkAndPackData (dbTransaction,
                                                             processStepId,
                                                             mpForm.getStandardUnitCost(),
                                                             mpForm.getPoFrequency(),
                                                             mpForm.getTargetYield(),
                                                             mpForm.getLotScrapYieldLimit(),
                                                             procedureDocId,
                                                             mpForm.getVisualSystem(),
                                                             markingDiagramId,
                                                             mpForm.getPackingMethod());

	                         // Step 4.1
	                         // added by hareesh on 1st September 2003
	                         // To Update Product in Mark and FG Track Table and Test Bin Stepu
	                         //, when Product Name is changed in  Product Step
	                         // -- START --
                             if ( ( mpForm.getProductName() !=null ) && ( mpForm.getOldProductName() !=null ) ) 
                             {
	           	                  if( ! mpForm.getOldProductName().trim().equals( mpForm.getProductName().trim() ) )
	           	                  {
                                   		// since up to this mark_FG_track_table does not contains the process_step_id  of Mark_AND_PACK
                                  	 	ProcessTrackDAO.updateMarkAndPackTrackProductName(dbTransaction,
                                                                               -1, // processtep_id
                                                                               mpForm.getTrackId(),
                                                                               mpForm.getProductName(),
                                                                               mpForm.getOldProductName() );
                                  }
                             }
                           // -- END --


                            // Step 5
                            // Store Product Table information
                            ProductDao.saveProcessStepProduct (dbTransaction,
                                                                  processStepId,
                                                                  mpForm.getProductName(),
                                                                  mpForm.getBaseProductId());

                            // Step 6
                            // Update nextStepID in the previousStepID row
                            ProductDao.updateNextProcessStepId (dbTransaction, mpForm.getPreviousStepId(), processStepId);

                            // Step 7
                            // Save vendor locations
                            if ((locations != null) && (locations.size() > 0)) 
                            {
                                VendorLocationDAO.saveVendorLocations (dbTransaction, processStepId, locations.iterator());
                            }
				
							//Added by ravikanth on 18 Sep 2003 
							// Step 8		
							// Save Duplicate names into Product_Map_Table
							if( mpForm.getDupProductName() != null && mpForm.getDupProductName().length > 0 )
							{
								ProductDao.saveProductMap(dbTransaction , processStepId , mpForm.getDupProductName() , locations );
							}

                            // Added by hareesh on 7th October 2003
                            ProcessTrackDAO.updateMarkAndFG (dbTransaction, processStepId, mpForm.getTrackId(), mpForm.getPreviousStepName(),
                                    mpForm.getProductName(), ProcessTrackDAO.MARK_AND_PACK,"Inprocess");

                           	success = true; // added by hareesh on 8th September 2003
                     }
				}
				else
				{
                   // added by hareesh on 8th September 2003
                    // -- START --
                    // Step 0
                    // to check name "part number" whether it exists already for another product or not.

                     boolean result = false;
                     if ( ( mpForm.getProductName() !=null ) && ( mpForm.getOldProductName() !=null ) ) 
                     {
                            if( ! mpForm.getOldProductName().trim().equals( mpForm.getProductName().trim() ) )
                            {
                                 result = ProcessTrackDAO.checkPartNumberExistsInTestBinAndFGBraodAndKit ( mpForm.getProductName().trim());
                            }
                     }

                     if (result == true )
                     {
                         errors.put( "Duplicate Part Number","Another Product has already present with this Part Number : "+ mpForm.getProductName().trim());
                     }
                     if ((errors != null) && (errors.isEmpty() == false)) 
                     {
                        request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
                     }
                     else 
                     {
                     // -- END --

                            //Step 1: Update Process Step Table
                            ProcessStep.updateProcessStepID(dbTransaction,mpForm.getStepName(),STEP_TYPE,mpForm.getComments(),processStepId);

                             //Step 2
                             //Update Product table
                             ProductDao.updateProcessStepProduct(dbTransaction,processStepId,mpForm.getProductName(),
                                                           mpForm.getBaseProductId());

                             // Step 3
                            // Upload procedure document
                            int procedureDocId = Upload.getProcedureDocID (dbTransaction,
                                                                              STEP_TYPE, // Mark & Pack
                                                                              mpForm.getProcedureDocNumber(),
                                                                              mpForm.getProcedureDocFile());

                            // Step 4
                            // Upload marking diagram file
                            int markingDiagramId = Upload.getMarkingDiagramDocID (dbTransaction,
                                                                                     STEP_TYPE, // Mark & Pack
                                                                                     mpForm.getMarkingDiagramNumber(),
                                                                                     mpForm.getMarkingDiagramFile());

                            // STEP 5
                            // Update Mark_Pack Table
                            MarkAndPackDAO.updateMarkAndPackData (dbTransaction,
                                                             processStepId,
                                                             mpForm.getStandardUnitCost(),
                                                             mpForm.getPoFrequency(),
                                                             mpForm.getTargetYield(),
                                                             mpForm.getLotScrapYieldLimit(),
                                                             procedureDocId,
                                                             mpForm.getVisualSystem(),
                                                             markingDiagramId,
                                                             mpForm.getPackingMethod());

                            // Step 5.1
                            // added by hareesh on 26th August 2003
                            // To Update Product in Mark And FG Track Table, when Product Name is changed
                            // in Product Step
                            // -- START --
                            if ( ( mpForm.getProductName() !=null ) && ( mpForm.getOldProductName() !=null ) ) {

                                 if( ! mpForm.getOldProductName().trim().equals( mpForm.getProductName().trim() ) ){

                                    ProcessTrackDAO.updateMarkAndPackTrackProductName(dbTransaction,
                                                                                processStepId,
                                                                                mpForm.getTrackId(),
                                                                                mpForm.getProductName(),
                                                                                mpForm.getOldProductName() );
                                 }
                            }
                            // -- END --


                            // Step 6
                            // Update Product Table information
                            ProductDao.updateProcessStepProduct (dbTransaction,
                                                                  processStepId,
                                                                  mpForm.getProductName(),
                                                                  mpForm.getBaseProductId());

                            // Step 7
                            // Delete and Save vendor locations
                            VendorLocationDAO.deleteVendorLocations(dbTransaction,processStepId);
                            if ((locations != null) && (locations.size() > 0)) {
                                VendorLocationDAO.saveVendorLocations (dbTransaction, processStepId, locations.iterator());
                            }
                            
							//Added by ravikanth on 18 Sep 2003 
							// Step 8		
							// Save Duplicate names into Product_Map_Table
							if( mpForm.getDupProductName() != null && mpForm.getDupProductName().length > 0 )
							{
								ProductDao.saveProductMap(dbTransaction , processStepId , mpForm.getDupProductName() , locations );
							}
	                        success = true; // added by hareesh on 8th September 2003
                     }

				}
				// End transaction 
                
                // success = true; removed by hareesh on 8th september 2003
            }
            
            catch (Exception e) {
                e.printStackTrace();
            }
            
            finally 
            {
                // Rollback or Commit the Transaction
            
                if (success == true) {
                    dbTransaction.commit();
                }
                else {
                    dbTransaction.rollback();
                }
            }
            
           
            // If sucessful, go to transport_locations page
            if (success == true) {
                request.setAttribute ("processStepId", processStepId+"");                  // 
                request.setAttribute ("previousStepId", mpForm.getPreviousStepId()+"");  // 
                request.setAttribute ("trackId", mpForm.getTrackId()+"");                  //
                request.setAttribute ("productName", mpForm.getProductName());            // To be used in transport_locations page
                request.setAttribute ("previousStepName", mpForm.getPreviousStepName()); //
                request.setAttribute ("stepName", mpForm.getStepName());                   //
                request.setAttribute ("baseProductId", mpForm.getBaseProductId()+"");       //
                request.setAttribute ("comingFrom", "MARK_AND_PACK");                     // 
                               
                return (mapping.findForward("success"));
            }
            
            // else send the user back to Mark and Pack
            // added by hareesh on 27th september 2003
            // -- START --
            ArrayList vendorLocations = getAllVendorLocations(request);
            if (vendorLocations == null){
               if(processStepId!=-1)
                {
                    vendorLocations = VendorDAO.getMarkAndPackLocations (processStepId);
                }
                else
                {
                    vendorLocations = VendorDAO.getMarkAndPackLocations ();
                }
            }
            request.setAttribute ("vendorLocations", vendorLocations );
            // -- END --
            return (mapping.findForward("failure"));
        }
        
        
        int processStepId = Integer.parseInt (request.getParameter ("processStepID"));
        int trackId = -1;
        String trackIdStr = request.getParameter ("trackID");
        if ((trackIdStr != null) && (trackIdStr.trim().length() != 0)) {
            trackId = Integer.parseInt (trackIdStr);
        }

        String previousStepName = request.getParameter ("previousStepName"); // added by hareesh on 7th October 2003

        MarkAndPackForm mpForm = null;
        ArrayList vendorLocations = null;
        
        if (processStepId == -1) {  // New 

            String stepName = request.getParameter ("stepName");
            //String previousStepName = request.getParameter ("previousStepName"); // changed by hareesh on 7th October 2003
            String productName = request.getParameter ("productName");
            int baseProductId = Integer.parseInt (request.getParameter ("baseProductID"));
            int previousStepId = Integer.parseInt (request.getParameter ("previousStepID"));
            
            mpForm = new MarkAndPackForm();
            mpForm.setStepName (stepName);
            mpForm.setProductName (productName);
            mpForm.setBaseProductId (baseProductId);
            mpForm.setPreviousStepId (previousStepId);
            mpForm.setTrackId (trackId);
            mpForm.setPreviousStepName (previousStepName);

            // Added by hareesh on 2nd September 2003
             mpForm.setOldProductName(productName);


            vendorLocations = VendorDAO.getMarkAndPackLocations();
        }
        else {  // Existing
            mpForm = MarkAndPackDAO.loadMarkAndPackData (processStepId);
            mpForm.setTrackId (trackId);
            mpForm.setProcessStepId (processStepId);
            mpForm.setPreviousStepName (previousStepName); // added by hareesh on 7th October 2003
            vendorLocations = VendorDAO.getMarkAndPackLocations (processStepId);
        }
        
        request.setAttribute ("vendorLocations", vendorLocations);
        request.setAttribute ("markAndPackForm", mpForm);
            
        return (mapping.findForward("show"));
    }
    
    
    private ArrayList getVendorLocations (HttpServletRequest request) {
        
        ArrayList vendorLocations = new ArrayList();
        
        String[] locationName = request.getParameterValues("locationName");
        if (locationName == null) {
            return null;
        }
        
	String[] priority = request.getParameterValues("priority");
	String[] locationID = request.getParameterValues("locationID");;
	String[] split = request.getParameterValues("split");
	String[] capacityWeek = request.getParameterValues("capacityWeek");
	String[] normalCost = request.getParameterValues("normalCost");
	String[] expressCost = request.getParameterValues("expressCost");
	String[] normalCycleTime = request.getParameterValues("normalCycleTime");
	String[] expressCycleTime = request.getParameterValues("expressCycleTime");

        VendorLocation location = null;
        for (int i=0; i<locationName.length; i++) {

            if (request.getParameter("select_"+i) != null) {    // check if this row was enabled by the user or not
                                                                    // save only if its enabled
                
                // changed by hareesh on 25th August 2003
                // -- START --
               /*location = new VendorLocation (priority[i],
                                                 locationName[i],
                                                 locationID[i],
                                                 split[i],
                                                 capacityWeek[i],
                                                 Float.parseFloat(normalCost[i]),
                                                 Float.parseFloat(expressCost[i]),
                                                 normalCycleTime[i],
                                                 expressCycleTime[i]);*/
                location = new VendorLocation();
                location.setPriority( ( priority[i] != null && priority[i].trim().length() != 0) ? priority[i] : "0" );
                location.setLocationName( locationName[i] );
                location.setLocationID( locationID[i] );
                location.setSplit( ( split[i] != null && split[i].trim().length() != 0) ? split[i] : "0" );
                location.setCapacityWeek( ( capacityWeek[i] != null && capacityWeek[i].trim().length() != 0) ? capacityWeek[i] : "0" );
                location.setNormalCost( Float.parseFloat ( ( normalCost[i] != null && normalCost[i].trim().length() != 0) ? normalCost[i] : "0.0" ) );
                location.setExpressCost( Float.parseFloat( expressCost[i] != null && expressCost[i].trim().length() != 0 ? expressCost[i] : "0.0" ) ) ;
                location.setNormalCycleTime(( normalCycleTime[i] != null && normalCycleTime[i].trim().length() != 0) ? normalCycleTime[i] : "0" );
                location.setExpressCycleTime(( expressCycleTime[i] != null && expressCycleTime[i].trim().length() != 0) ? expressCycleTime[i] : "0"  );
                // --- END --
                vendorLocations.add (location);
            }
        }
        
        return vendorLocations;
    }

    // added by hareesh on 8th Septemeber 2003
    // -- START --

    private ArrayList getAllVendorLocations (HttpServletRequest request) {

        ArrayList vendorLocations = new ArrayList();

        String[] locationName = request.getParameterValues("locationName");
        if (locationName == null) {
            return null;
        }

	    String[] priority = request.getParameterValues("priority");
	    String[] locationID = request.getParameterValues("locationID");;
	    String[] split = request.getParameterValues("split");
	    String[] capacityWeek = request.getParameterValues("capacityWeek");
	    String[] normalCost = request.getParameterValues("normalCost");
	    String[] expressCost = request.getParameterValues("expressCost");
	    String[] normalCycleTime = request.getParameterValues("normalCycleTime");
	    String[] expressCycleTime = request.getParameterValues("expressCycleTime");

        VendorLocation location = null;
        for (int i=0; i<locationName.length; i++) {

                // changed by hareesh on 25th August 2003
                // -- START --
               /*location = new VendorLocation (priority[i],
                                                 locationName[i],
                                                 locationID[i],
                                                 split[i],
                                                 capacityWeek[i],
                                                 Float.parseFloat(normalCost[i]),
                                                 Float.parseFloat(expressCost[i]),
                                                 normalCycleTime[i],
                                                 expressCycleTime[i]);*/
                location = new VendorLocation();
                location.setPriority( ( priority[i] != null && priority[i].trim().length() != 0) ? priority[i] : "0" );
                location.setLocationName( locationName[i] );
                location.setLocationID( locationID[i] );
                location.setSplit( ( split[i] != null && split[i].trim().length() != 0) ? split[i] : "0" );
                location.setCapacityWeek( ( capacityWeek[i] != null && capacityWeek[i].trim().length() != 0) ? capacityWeek[i] : "0" );
                location.setNormalCost( Float.parseFloat ( ( normalCost[i] != null && normalCost[i].trim().length() != 0) ? normalCost[i] : "0.0" ) );
                location.setExpressCost( Float.parseFloat( expressCost[i] != null && expressCost[i].trim().length() != 0 ? expressCost[i] : "0.0" ) ) ;
                location.setNormalCycleTime(( normalCycleTime[i] != null && normalCycleTime[i].trim().length() != 0) ? normalCycleTime[i] : "0" );
                location.setExpressCycleTime(( expressCycleTime[i] != null && expressCycleTime[i].trim().length() != 0) ? expressCycleTime[i] : "0"  );
                // --- END --
                if (request.getParameter("select_"+i) != null) {
                    location.setSelect ("on");
                }
                vendorLocations.add (location);
        }
        return vendorLocations;
    }

    // -- END --

}